package com.flong.modules.utils;

import java.lang.reflect.Field;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
/**
 * 
 * @Description	DBHelper
 * @ClassName	DBHelper
 * @Date		2017年2月23日 下午2:01:10
 * @Author		liangjilong
 */
@SuppressWarnings("all")
public class DBHelper {
	private static DBHelper instance = null;
	private static Connection conn = null;
	private static Statement stmt = null;
	private static PreparedStatement preparedStatement = null;
	private static CallableStatement callableStatement = null;
	private static ResultSet rs = null;
	static {
		try {
			String driverClass = PropertiesHelper.get("jdbc.driver");//驱动
			String connectionUrl = PropertiesHelper.get("jdbc.url");//链接
			String username = PropertiesHelper.get("jdbc.username");//用户名
			String password = PropertiesHelper.get("jdbc.password");//密码
			Class.forName(driverClass);
			conn = DriverManager.getConnection(connectionUrl, username, password);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	} 

	
	/**建立单例模式
	 * Single
	 * @return
	 */
	public static DBHelper getInstance() {
		if (instance == null) {
			synchronized (DBHelper.class) {
				instance = new DBHelper();
			}
		}
		return instance;
	}
	
	/**
	 * @return:Connection
	 */
	public static Connection getConnection() {
		try {
			String driverClass = PropertiesHelper.get("jdbc.driver");
			String connectionUrl = PropertiesHelper.get("jdbc.url");
			String username = PropertiesHelper.get("jdbc.username");
			String password = PropertiesHelper.get("jdbc.password");
			Class.forName(driverClass);
			conn = DriverManager.getConnection(connectionUrl, username, password);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	/**
	 * @Description 查询
	 * @Author		liangjilong
	 * @Date		2017年2月23日 下午2:09:32
	 * @param sql
	 * @param params
	 * @return 		参数
	 * @return 		ResultSet 返回类型
	 */
	public static ResultSet query(String sql, List<Object> params) {
		try {
			PreparedStatement psmt = conn.prepareStatement(sql);
			if(params != null) {
				for (int i = 0; i < params.size(); i++) {
					psmt.setObject(i+1, params.get(i));
				}
			}	
			return psmt.executeQuery();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * @Description 更新
	 * @Author		liangjilong
	 * @Date		2017年2月23日 下午2:09:44
	 * @param sql
	 * @param params 		参数
	 * @return 		void 返回类型
	 */
	public static void update(String sql, List<Object> params) {
		try {
			PreparedStatement psmt = conn.prepareStatement(sql);
			if(params != null) {
				for (int i = 0; i < params.size(); i++) {
					psmt.setObject(i+1, params.get(i));
				}
			}	
			psmt.executeUpdate();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	/**
     * 批量更新数据
     * @param sqlList
     *            一组sql
     * @return
     */
    public static int[] batchUpdate(List<String> sqlList) {
        int[] result = new int[] {};
        Statement statenent = null;
        try {
        	conn = getConnection();
            conn.setAutoCommit(false);
            statenent = conn.createStatement();
            for (String sql : sqlList) {
                statenent.addBatch(sql);
            }
            result = statenent.executeBatch();
            conn.commit();
        } catch (SQLException e) {
            try {
                conn.rollback();
            } catch (SQLException e1) {
                throw new ExceptionInInitializerError(e1);
            }
            throw new ExceptionInInitializerError(e);
        } finally {
        	 free(statenent, null);
        }
        return result;
    }
    /**
	 * 支持批量处理delete update insert
	 * 
	 * @param sqls
	 * @return
	 */
	public int supportsBatch(Object[] sqls) {
		try {
			conn = DBHelper.getInstance().getConnection();
			conn.setAutoCommit(false);
			DatabaseMetaData dma = conn.getMetaData();
			if (dma.supportsBatchUpdates()) {
				int bufferSize = 0;
				stmt = conn.createStatement();
				for (int i = 0; i < sqls.length; i++) {
					bufferSize++;
					if ((bufferSize + 1) % 100 == 0) {
						stmt.addBatch(sqls[i].toString());
						conn.commit();
						stmt.clearBatch();
					}
				}
				int[] rows = stmt.executeBatch();
				conn.commit();
				return rows.length;
			} else {
				return sqls.length;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			releaseAll(null, stmt, conn);
		}
		return 0;
	}
	/***
	 * 释放资源...
	 * 
	 * @param rs
	 * @param st
	 * @param conn
	 */
	public static void releaseAll(ResultSet rs, Statement st, Connection conn) {
		try {
			if (rs != null)
				rs.close();
			if (st != null)
				st.close();
			if (conn != null)
				conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 释放所有连接
	 */
	public static void releaseAll() {
		if (rs != null) {
			try {
				rs=null;
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (preparedStatement != null) {
			try {
				preparedStatement=null;
				preparedStatement.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (conn != null) {
			try {
				conn=null;
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	/**
     * 释放资源
     */
    public static void release() {
        release(null);
    }
    /**
     * 释放资源
     * @param rs
     *            结果集
     */
    public static void release(ResultSet rs) {
    	release(conn, preparedStatement, rs);
    }
    /**
     * 释放连接
     * @param conn
     */
    private static void releaseConnection(Connection conn) {
        try {
            conn.close();
            conn = null;
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 释放statement
     * @param statement
     */
    private static void releaseStatement(Statement statement) {
        try {
            statement.close();
            statement = null;
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 释放resultset
     * @param rs
     */
    private static void releaseResultSet(ResultSet rs) {
        try {
            rs.close();
            rs= null;
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 释放资源,节省空间
     * @param conn
     * @param statement
     * @param rs
     */
    public static void release(Connection conn, Statement statement, ResultSet rs) {
        if (rs != null) {
            releaseResultSet(rs);
        }
        if (statement != null) {
            releaseStatement(statement);
        }
        if (conn != null) {
            releaseConnection(conn);
        }
    }
    /**
	 * @Description ResultSetMetaData将数据反射到实体类中
	 * @Author		liangjilong
	 * @Date		2017年3月1日 上午9:06:27
	 * @param rs
	 * @param clazz
	 * @return
	 * @throws Exception 		参数
	 * @return 		List<T> 返回类型
     */
    public static <T> List<T> convertToEntitys(ResultSet rs, Class<T> clazz) {
        List<T> fieldList = null;
		try {
			fieldList = new ArrayList<T>();
			T t = null;
			while (rs.next()) {
			    t = clazz.newInstance();
			    ResultSetMetaData rsmd = rs.getMetaData();//获取结果集
			    int count = rsmd.getColumnCount();//获取列总数
			    for (int i = 1; i <= count; i++) {
			        String name = rsmd.getColumnName(i);//获取列名
			        if(ObjectUtil.isNotEmpty(name)){
			        	//Oracle查询出来的字段是大写，所以要转换为小写
			        	String fieldName = name.toLowerCase();
			        	Field field = clazz.getDeclaredField(fieldName);
			        	field.setAccessible(true);//把私有private属性设置为共有public
			        	field.set(t, rs.getObject(fieldName));
			        }
			    }
			    fieldList.add(t);
			}
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			//查完数据把结果集关闭，减少链接数据库资源访问
			releaseResultSet(rs);
		}
        return fieldList;
    }
    /**
     * 释放资源
     * @param statement
     * @param rs
     */
    public static void free(Statement statement, ResultSet rs) {
    	release(conn, statement, rs);
    }
    
    /**
	 * @Description 获取数据名称
	 * @Author		liangjilong
	 * @Date		2017年2月23日 下午2:09:10
	 * @return 		参数
	 * @return 		String 返回类型
     */
    public static String getDataBaseName(){
       String DB_NAME = PropertiesHelper.get("jdbc.url").substring(
    		  PropertiesHelper.get("jdbc.url").lastIndexOf("/")+1,
    		  PropertiesHelper.get("jdbc.url").indexOf("?") == -1? 
    	      PropertiesHelper.get("jdbc.url").length():
		     PropertiesHelper.get("jdbc.url").indexOf("?"));
     return DB_NAME;
    }
}
